package com.bjpowernode.service.impl;

import com.bjpowernode.configs.MyThreadLocal;
import com.bjpowernode.service.UserService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
/***
 * 自定义认证类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 把数据存到ThreadLock中
        MyThreadLocal.threadLocal.set(username);

        com.bjpowernode.domain.User user = userService.findUserName(username);
        // 可以在自己的实体类上面去实现UserDetails,也可以直接使用默认的方法
        // 在很多地方需要使用到用户id,我们就不存入用户名到上下文,把用户id存入到上下文中,没有权限存入一个空的集合
        User loginUser = new User(user.getId().toString(),user.getPassword(), new HashSet<>());
        return loginUser;
    }
}
